package com.jt.controller;

import com.jt.entity.Admin;
import com.jt.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

@Controller
public class AdminController {

    private static final String KAPTCHA_SESSION_KEY = null;


    @Autowired
    private AdminService adminService;

    @RequestMapping("/login")
    public String login(String name,String password, ModelMap modelMap,HttpServletRequest request){
        Admin login = adminService.login(name, password);
        if (login!=null){
            request.getSession().setAttribute("login",login);
            return "frame";
        }
        modelMap.addAttribute("msg","用户名或密码错误");
        return "login";
    }

    // 登陆 @RequestParam(required=false) 表示此参数可用没有 也可以有
    @PostMapping(value = "login.mvc")
    public ModelAndView login(Admin admin, HttpSession session, String code, @RequestParam(required=false)String rememberMe, HttpServletRequest request, HttpServletResponse response){
        ModelAndView view = new ModelAndView();
        // code 获取前端传递过来的验证码
        System.out.println(code);
        //获取客户端生成的验证码
        String codeGoogle =(String)session.getAttribute(KAPTCHA_SESSION_KEY);
        //删除客户端验证码
        session.removeAttribute(KAPTCHA_SESSION_KEY);

        Admin  sessionUser = adminService.login(admin.getName(), admin.getPassword());
        // 验证码和用户名密码都正确则登陆成功
        if (sessionUser!=null&&codeGoogle.equals(code)){

            session.setAttribute("admin",sessionUser);
            // 判断用户是否勾选记住密码单选框 如果是 调用 isMemory方法将用户名和密码保存到客户端
            System.out.println("rememberMe="+rememberMe);
            try {
                isMemory(rememberMe!=null,admin,request,response);
            } catch (UnsupportedEncodingException e) {
                System.out.println("设置字符集出错=>request.setCharacterEncoding()");
                e.printStackTrace();
            }
            view.setViewName("frame.jsp");
        }
        else {
            view.setViewName("login.jsp");
        }
        return view;
    }

    /**
     * 验证用户是否勾选记住按钮单选框
     * @param rememberMe 单选框的值
     * @param admin 当前登陆用户对象
     * @param request 请求对象
     * @param response 响应对象-
     * @throws UnsupportedEncodingException
     **/
    private void isMemory(boolean rememberMe, Admin admin, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        if(rememberMe){
            Cookie username=new Cookie("name", admin.getName());
            username.setPath("/");

            Cookie password=new Cookie("password",admin.getPassword());
            password.setPath("/");

            //设置账号和密码最长保存时间 单位是秒 1天=60*60*24 *需要保存的填数 保存7填为=(60*60*24)*7
            username.setMaxAge((60*60*24)*7);
            password.setMaxAge((60*60*24)*7);

            // 将cookie返回给客户端
            response.addCookie(username);
            response.addCookie(password);

        }else{
            // 遍历cookie中的username和password 如果用户没有选择记住密码 则删除客户端的密码
            Cookie[] cookies= request.getCookies();
            if (cookies!=null){
                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName().equals("name")||cookies[i].equals("password")){
                        System.out.println("删除掉的cookie----》"+cookies[i].getName());
                        cookies[i].setMaxAge(0);
                        cookies[i].setPath("/");
                        response.addCookie(cookies[i]);
                    }
                }
            }

        }

    }


}
